<?php

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class UserGroup extends Eloquent{

	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'user_group';
	protected $validator = null;

	public function saveData($data){
		$usergroup = new UserGroup;

		if(isset($data['id']) && $data['id'] > 0){
			$usergroup = UserGroup::firstOrNew(array('id' => $data['id']));
		}

		$usergroup->group       = $data['group'];
		$usergroup->description = $data['description'];
		$usergroup->save();
		Cache::forget('usergroup-all-data');
		
		return $usergroup;
	}

	public function getAllData(){
		if(!Cache::has('usergroup-all-data')){
			$data = UserGroup::all();
			Cache::put('usergroup-all-data', $data, 30);
		}

		$data = Cache::get('usergroup-all-data');

		return $data;
	}

	public function validator($data){
		$id = (isset($data['id']))? $data['id'] : "NULL";

		$rules = array(
			'group'       => array('required', 'unique:user_group,group,' . $id . ',id,deleted_at,NULL', 'alpha_num_spaces'),
			'description' => array('alpha_num_spaces'),
			);

		$this->validator = Validator::make($data, $rules);

		return $this->validator;
	}

	public function getErrorMessages(){
		$messages = $this->validator->messages();
		
		$result   = array();

		foreach($messages->all() as $m){
			$result[]['message'] = $m;
		}

		return $result;
	}
}
